﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GGJ_DKG
{
    class Animation
    {
        public Texture2D Texture { get; set; }

        public Vector2 FrameCoordinates { get; set; }

        public Vector2 FrameSize { get; set; }

        private int currentFrameX;

        public Vector2 Position;

        private readonly int _msPerFrame;

        public bool Flip;

        private SpriteEffects spriteEffects;

        private int timeSinceLastUpdate;


        public Animation(Texture2D texture, Vector2 position, Vector2 frameCoordinates,
                Vector2 frameSize, int msPerFrame)
        {

            Texture = texture;
            FrameCoordinates = frameCoordinates;
            FrameSize = frameSize;
            Position = position;
            _msPerFrame = msPerFrame;
        }

        public void Update(GameTime gameTime)
        {
            timeSinceLastUpdate += gameTime.ElapsedGameTime.Milliseconds;

            if (timeSinceLastUpdate > _msPerFrame)
            {
                timeSinceLastUpdate -= _msPerFrame;

                if (currentFrameX >= FrameCoordinates.X)
                {
                    currentFrameX = 0;
                }

                currentFrameX++;

            }
            spriteEffects = Flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None;

        }

        public void Draw(SpriteBatch spriteBatch)
        {

            spriteBatch.Draw(Texture, Position, new Rectangle((int)(currentFrameX * FrameSize.X), 
                (int)(FrameCoordinates.Y * FrameSize.Y), (int)FrameSize.X, (int)FrameSize.Y), 
                Color.White, 0, new Vector2(FrameSize.X / 2, FrameSize.Y / 2), 1, spriteEffects, 0);

        }
    }
}
